var primaryPollInterval = 1000; //milliseconds
var secondaryPollInterval = 10000; // milliseconds
var pollTakeoverTimeout = 5000; //milliseconds until a secondary poller will takeover primary polling

var baseURL = "http://wave-notes.appspot.com/images/";

var presentation = null;
var presentationKey = "";
var listOfPresentations = [];
var preferredParticipants = [];
var currentParticipants = [];

var numberOfSlides = 0;
var slideIndex;
var firstLoad = true;

var presentationState = null;

var peopleNotes = {};

var echoTimer = null;
var echoTimerInterval = 1000;

var loadedSmall = [];
var loadedLarge = [];

var imageSize = 'small';
var currentLayout = 'below';
var currentSort = 'time';

function eId(id) {
	return document.getElementById(id);
}

function eName(name) {
	return document.getElementsByName(name)[0];
}

function eNames(name) {
	return document.getElementsByName(name);
}

function eNamesSetDisplay(name, display) {
	var elements = eNames(name);
	for(var i=0; i<elements.length; i++)
		elements[i].style.display = display;
}

function debugLog(log) {
	eId('debugLog').innerHTML += log + '<br/>';
	gadgets.window.adjustHeight();
}

function enableDisableStart() {
	if(presentationKey != "" && eId('participant_textarea').value.length > 0) {
		//eId('start_presentation_div').style.display = 'block';
	}
	else {
		eId('start_presentation_div').style.display = 'none';
	}
}

function getIsSynchronized() {
	return eId('stay_synchronized').disabled;
}

function storeSelectedPresentation() {
	if(presentationState != "selection") {
		debugLog('not selection:'+presentationKey);
		return;
	}
	var selector = eId('presentation_selector');
	if(selector.selectedIndex < 0) {
		showSelectPresentation(true);
	}
	else { 
		showSelectPresentation(false);
		var data = {};
		data["presentationKey"] = presentationKey;
		wave.getState().submitDelta(data);
	}
	enableDisableStart();
}

function alertStartDisabled() {
	if(presentationKey == "")
		alert("No presentation selected");
	else if(eId('participant_textarea').value.length == 0)
		alert('No Participants Entered');
}

function refreshNumberOfSlides() {
	var slideNavigationHTML = "";
	for(var i=0; i<numberOfSlides; i++)
		slideNavigationHTML += "<option>"+(i+1)+"</option>";
	eId('slide_navigation').innerHTML = slideNavigationHTML;
	eId('number_of_slides_span').innerHTML = ""+numberOfSlides;
	refreshNextSlideButton();
	refreshPrevSlideButton();
}

function refreshPresentationList() {
	var refreshCount = wave.getState().get("refreshPresentations");
	if(refreshCount == null)
		refreshCount = 0;
	else
		refreshCount = parseInt(refreshCount);
	wave.getState().submitValue("refreshPresentations",refreshCount+1);
}

function updateListOfPresentations(listOfPresentations) {
	var optionsHTML = "";
	if(listOfPresentations!=null) {
		for(var i=0; i<listOfPresentations.length; i++) {
			optionsHTML += "<option value='"+listOfPresentations[i].id+"'"; 
			if(listOfPresentations[i].id == presentationKey)
				optionsHTML += " selected";
			optionsHTML += ">"+listOfPresentations[i].name+"</option>";
		}
	}
	eId('presentation_selector').innerHTML = optionsHTML;
	if(eId('presentation_selector').options.length > 0) {
		eId('no_presentations_found_div').style.display = 'none';
		if(presentationKey == "" && eId('presentation_selector').selectedIndex < 0) {
			showSelectPresentation(true);
		}
		else {
			showSelectPresentation(false);
		}
	}
	else {
		eId('no_presentations_found_div').style.display = 'block';
		eId('select_presentation_div').style.display = 'none';
	}
}

function toggleParticipantSelected(participantId) {
	if(eId(participantId+'_div').className == 'participant_selected') {
		eId(participantId+'_img').className = 'check_no';
		eId(participantId+'_div').className = 'participant_not_selected';
	}
	else {
		eId(participantId+'_img').className = 'check_yes';
		eId(participantId+'_div').className = 'participant_selected';
	}
	storeParticipantLists();
}

function updateParticipantList() {
	var newPreferredParticipants = [];
	currentParticipants = [];
	for(var i=0; i<preferredParticipants.length; i++) {
		if(eId(preferredParticipants[i].id+'_div')) {
			newPreferredParticipants.push(preferredParticipants[i]);
			if(eId(preferredParticipants[i].id+'_div').className == 'participant_selected')
				currentParticipants.push(preferredParticipants[i].id);
		}
	}
	var waveParticipants;
	try {
		waveParticipants = eval("("+wave.getState().get("preferredParticipants")+")");
	} catch(err) {
	}
	if (waveParticipants != null)
	{
		for(var i=0; i<waveParticipants.length; i++) {
			var participant;
			try { participant = eval("("+waveParticipants[i]+")"); } catch(err) {}
			if(!participant)
				continue;
			if(!containsParticipant(newPreferredParticipants,participant)) {
				newPreferredParticipants.push(participant);
				if(eId(participant.id+'_div') && 
						eId(participant.id+'_div').className == 'participant_selected')
					currentParticipants.push(participant.id);
			}
		}
	}
	var participantDOMs = eNames('participant_selector');
	if(participantDOMs) {
		for(var i=0; i<participantDOMs.length; i++) {
			var waveParticipant = wave.getParticipantById(participantDOMs[i].id.substr(0,participantDOMs[i].id.length-4));
			if(waveParticipant == null)
				continue;
			var participant = {"id":waveParticipant.getId(), 
				"displayName":waveParticipant.getDisplayName(),
				"thumbnailURL":waveParticipant.getThumbnailUrl()};
			if(containsParticipant(newPreferredParticipants,participant))
				continue;
			newPreferredParticipants.push(participant);
			if(participantDOMs[i].className == 'participant_selected')
				currentParticipants.push(participant.id);
		}
	}
	preferredParticipants = newPreferredParticipants;
	updateParticipantObjects();
}


function storeParticipantLists() {
	
	var data = {};
	updateParticipantList();
	data["preferredParticipants"] = JSON.stringify(preferredParticipants,replacer);
	data["currentParticipants"] = JSON.stringify(currentParticipants,replacer);
	wave.getState().submitDelta(data);
	enableDisableStart();
}

function createParticipantHTML(participant, selected) {
	var html = "<tr id='"+participant.id+"_div' name='participant_selector' class='participant_";
	if(selected)
		html += "selected'>";
	else
		html += "not_selected'>";
	html += "<td id='"+participant.id+"_img' onClick='toggleParticipantSelected(\""+participant.id+"\");' class='check_";
	if(selected)
		html += "yes";
	else
		html += "no";
	html += "'>&nbsp;</td>";
	html += "<td onClick='toggleParticipantSelected(\""+participant.id+"\");'><img class='participant_select_image' src='"+participant.thumbnailURL+"' /></td><td onClick='toggleParticipantSelected(\""+participant.id+"\");' class='participant_select_name'>";
	if(participant.displayName != participant.id)
		html += participant.displayName + " (" + participant.id + ")";
	else 
		html += participant.id;
	html += "</td></tr>";
	return html;
}

function updateParticipantObjects() {
	var participantListHTML = "<table style='border-collapse: collapse;'>";
	var textareaValue = "";
	
	sortParticipants(preferredParticipants);

	for(var i=0; i<preferredParticipants.length; i++) {
		if(preferredParticipants[i].id != wave.getHost().getId() && preferredParticipants[i].id != "wave-notes@appspot.com") {
			textareaValue += preferredParticipants[i].id+"\n";
			participantListHTML += createParticipantHTML(preferredParticipants[i],contains(currentParticipants,preferredParticipants[i].id));
		}
	}
	participantListHTML += "</table>"
	eId('participant_selection_div').innerHTML = participantListHTML;
	eId('participant_textarea').value = textareaValue;
}

function contains(arr, elm) {
	if(arr == null)
		return false;
	for(var i=0; i<arr.length; i++)
		if(arr[i] == elm)
			return true;
	return false;
}

function containsParticipant(arr, elm) {
	if(arr == null)
		return false;
	for(var i=0; i<arr.length; i++)
		if(elm && elm.id && arr[i].id == elm.id)
			return true;
	return false;
}

function getImageHeight() {
	if(imageSize == 'tiny')
		return 180;
	else if(imageSize == 'small') 
		return 300;
	else if(imageSize == 'medium')
		return 480;
	else if(imageSize == 'large')
		return 780;
	return 300;
}

function updateImageSize() {
	var imageHeight = getImageHeight();
	eId('slide_image').style.height = imageHeight + 'px';
	eId('slide_holder').style.height = (imageHeight+5) + 'px';
	updateNotesSize();
	gadgets.window.adjustHeight();
}

function selectSize(size) {
	eId("size_"+imageSize).src = baseURL+"normal.png";
	imageSize = size;
	eId("size_"+size).src = baseURL+"selected.png";
	updateImageSize();
}

function hoverSize(size) {
	if(imageSize != size)
		eId("size_"+size).src = baseURL+"hovered.png";
}

function unhoverSize(size) {
	if(imageSize != size)
		eId("size_"+size).src = baseURL+"normal.png";
}

function selectLayout(layout) {
	if(currentLayout != layout) {
		eId("layout_"+currentLayout).src = baseURL+currentLayout+".png";
		currentLayout = layout;
		eId("layout_"+layout).src = baseURL+"selected_"+layout+".png";
		toggleSideBySide();
	}
}

function hoverLayout(layout) {
	if(currentLayout != layout)
		eId("layout_"+layout).src = baseURL+"hovered_"+layout+".png";
}

function unhoverLayout(layout) {
	if(currentLayout != layout)
		eId("layout_"+layout).src = baseURL+layout+".png";
}

function selectSort(sort) {
	if(currentSort != sort) {
		eId("sort_"+currentSort).src = baseURL+currentSort+".png";
		currentSort = sort;
		eId("sort_"+sort).src = baseURL+"selected_"+sort+".png";
		refreshNotes();
	}
}

function hoverSort(sort) {
	if(currentSort != sort)
		eId("sort_"+sort).src = baseURL+"hovered_"+sort+".png";
}

function unhoverSort(sort) {
	if(currentSort != sort)
		eId("sort_"+sort).src = baseURL+sort+".png";
}

function updateNotesSize() {
	var totalWidth = eId('floating_right').offsetLeft;
	if (currentLayout == 'sideBySide') {
		var imageWidth = (getImageHeight()/3) * 4;
		if(imageWidth < totalWidth / 2)
			imageWidth = totalWidth / 2;
		var notesWidth = totalWidth - imageWidth;
		eId('side_by_side_holder').style.width = notesWidth + 'px';
		eId('slide_holder').style.width = imageWidth + 'px';
		eId('notes_textarea').cols = (notesWidth - 100)/10;
		eId('notes_container').style.height = (getImageHeight()-90)+'px';
	}
	else {
		eId('side_by_side_holder').style.width = "1px";
		eId('slide_holder').style.width = totalWidth + 'px';
		eId('notes_textarea').cols = 50;
		eId('notes_container').style.height = '210px';
	}
}

function toggleSideBySide() {
	var sideBySideHTML = eId('side_by_side_holder').innerHTML;
	var lowerNotesHTML = eId('notes_section').innerHTML;
	if(lowerNotesHTML == "") {
		eId('notes_section').innerHTML = sideBySideHTML;
		eId('side_by_side_holder').innerHTML = "";
	}
	else {
		eId('side_by_side_holder').innerHTML = lowerNotesHTML;
		eId('notes_section').innerHTML = "";
	}
	updateNotesSize();
}

function replacer(key, value) {
	if (typeof value === 'number' && !isFinite(value)) {
		return String(value);
	}
	return value;
}

function echoNote() {
	doSynchronization(false);
	eId('finish_note_button').disabled = (eId('notes_textarea').value.length == 0);
	eId('cancel_note_button').disabled = eId('finish_note_button').disabled;
	if(echoTimer == null) {
		echoTimer = setTimeout('doEchoNote();',echoTimerInterval);
	}
}

function doEchoNote() {
	echoTimer = null;
	var participantId = wave.getViewer().getId();
	var participantsNotes = peopleNotes[participantId];
	var noteIndex = parseInt(eId("note_index").value);
	var currentNote;
	if(isNaN(noteIndex))
		noteIndex = 0;
	if(!participantsNotes)
		participantsNotes = {};
	if(!participantsNotes["slide_"+slideIndex])
		participantsNotes["slide_"+slideIndex] = [];
	if(!participantsNotes["slide_"+slideIndex][noteIndex])
		participantsNotes["slide_"+slideIndex][noteIndex] = {};
	currentNote = participantsNotes["slide_"+slideIndex][noteIndex];
	if(currentNote["finished"]) {
		currentNote = {};
		noteIndex++;
	}
	if(!currentNote["participantId"]) {
		currentNote["participantId"] = participantId;
		currentNote["displayName"] = wave.getViewer().getDisplayName();
		currentNote["time"] = wave.getTime();
		currentNote["finished"] = false;
	}
	eId('note_index').value = noteIndex;
	currentNote["text"] = eId('notes_textarea').value;
	participantsNotes["slide_"+slideIndex][noteIndex] = currentNote;
	wave.getState().submitValue(participantId+"_notes",JSON.stringify(participantsNotes));
}

function cancelNote() {
	var participantId = wave.getViewer().getId();
	var participantsNotes = peopleNotes[participantId];
	var noteIndex = parseInt(eId("note_index").value);
	var currentNote;
	if(isNaN(noteIndex))
		noteIndex = 0;
	if(!participantsNotes)
		participantsNotes = {};
	if(!participantsNotes["slide_"+slideIndex])
		participantsNotes["slide_"+slideIndex] = [];
	if(!participantsNotes["slide_"+slideIndex][noteIndex])
		participantsNotes["slide_"+slideIndex][noteIndex] = {};
	currentNote = participantsNotes["slide_"+slideIndex][noteIndex];
	if(!currentNote["finished"]) {
		currentNote["participantId"] = null;
		currentNote["displayName"] = null;
		currentNote["time"] = null;
		currentNote["finished"] = null;
		currentNote["text"] = null;
	}
	eId('note_index').value = noteIndex;
	eId('notes_textarea').value = "";
	participantsNotes["slide_"+slideIndex][noteIndex] = currentNote;
	wave.getState().submitValue(participantId+"_notes",JSON.stringify(participantsNotes));
	eId('finish_note_button').disabled = true;
	eId('cancel_note_button').disabled = true;
}

function finishNote() {
	if(echoTimer != null)
		clearTimeout(echoTimer);
	var participantId = wave.getViewer().getId();
	var participantsNotes = peopleNotes[participantId];
	var noteIndex = parseInt(eId("note_index").value);
	var currentNote;
	if(isNaN(noteIndex) || !participantsNotes || 
			!participantsNotes["slide_"+slideIndex] || 
			!participantsNotes["slide_"+slideIndex][noteIndex] ||
			participantsNotes["slide_"+slideIndex][noteIndex]["finished"] ||
			!participantsNotes["slide_"+slideIndex][noteIndex]["text"] ||
			participantsNotes["slide_"+slideIndex][noteIndex]["text"].length == 0)
		return;
	participantsNotes["slide_"+slideIndex][noteIndex]["finished"] = true;
	wave.getState().submitValue(participantId+"_notes",JSON.stringify(participantsNotes));
	eId('notes_textarea').value = "";
	eId('finish_note_button').disabled = true;
	eId('cancel_note_button').disabled = true;
	doSynchronization(true);
}

function aggregateNotes() {
	var aggregatedNotes = [];
	var slideI;
	for(slideI=0; slideI<numberOfSlides; slideI++)
		aggregatedNotes[slideI] = [];
	for(var participantId in peopleNotes)
		for(slideI=0; slideI<numberOfSlides; slideI++)
			if(peopleNotes[participantId]["slide_"+slideI])
				for(var i=0; i<peopleNotes[participantId]["slide_"+slideI].length; i++)
					if(peopleNotes[participantId]["slide_"+slideI][i] != null &&
							peopleNotes[participantId]["slide_"+slideI][i]["time"])
						aggregatedNotes[slideI][aggregatedNotes[slideI].length] = peopleNotes[participantId]["slide_"+slideI][i];
	var notesJSON = JSON.stringify(aggregatedNotes);
	wave.getState().submitValue("aggregatedNotes",notesJSON);
	//alert('Submitted: '+notesJSON);
}

function loadNoteInTextArea() {
	var participantId = wave.getViewer().getId();
	var participantsNotes = peopleNotes[participantId];
	var noteIndex = parseInt(eId("note_index").value);
	if(isNaN(noteIndex) || !participantsNotes || 
			!participantsNotes["slide_"+slideIndex] || 
			!participantsNotes["slide_"+slideIndex][noteIndex] ||
			participantsNotes["slide_"+slideIndex][noteIndex]["finished"])
		return;
	eId('notes_textarea').value = participantsNotes["slide_"+slideIndex][noteIndex]["text"];
}

function getDisplayName(participantId) {
	var participant = wave.getParticipantById(participantId);
	if(!participant)
		return participantId;
	if(participant == wave.getViewer())
		return "You";
	return participant.getDisplayName();
}

function getThumbnailSrc(participantId) {
	var participant = wave.getParticipantById(participantId);
	if(!participant)
		return "";
	return participant.getThumbnailUrl();
}

function repopulatePeopleNotes() {
	var participants = wave.getParticipants();
	if(participants)
		for(var i=0; i<participants.length; i++)
			if(wave.getState().get(participants[i].getId()+'_notes') != null) {
				peopleNotes[participants[i].getId()] = eval("("+wave.getState().get(participants[i].getId()+'_notes')+")");
			}
}

function startPresentation() {
	var data = {};
	data["preferredParticipants"] = JSON.stringify(eId("participant_textarea").value.split("\n"),replacer);
	data["presentationKey"] = presentationKey;
	data["presentationState"] = "preStart";
	wave.getState().submitDelta(data);
	primaryPoll(true);
}

function getCurrentImageURL(){
	return getImageURL(slideIndex);
}

function getImageURL(index) {
	if(index < 0 || isNaN(index))
		return "";
	if(presentation != null && presentation.slides != null && presentation.slides[index] != null 
			&& presentation.slides[index].slideUrl != null && presentation.slides[index].slideUrl != "")
		return presentation.slides[index].slideUrl;
	if(presentation != null && presentation.slideRoot != null && presentation.slideRoot != "")
		return presentation.slideRoot + "Slide" + (index+1) + ".PNG";
	var url = "http://wave-notes.appspot.com/slide?";
	if(presentation == null || presentation.slides == null 
			|| presentation.slides.length <= 0 || presentation.slides[index] == null)
		url += "presentationKey="+presentationKey+"&slideIndex="+index;
	else
		url += "slideKey="+presentation.slides[index].encodedKey;
	if(imageSize == 'tiny' || imageSize == 'small')
		url += "&size=small";
	return url;
}

function checkCurrentPreload() {
	checkPreload(slideIndex);
	if(slideIndex - 2 >= 0)
		checkPreload(slideIndex-2);
	if(slideIndex - 1 >= 0)
		checkPreload(slideIndex-1);
	if(slideIndex + 1 < numberOfSlides)
		checkPreload(slideIndex+1);
	if(slideIndex + 2 < numberOfSlides)
		checkPreload(slideIndex+2);
}

function checkPreload(index) {
	if(isNaN(index))
		return;
	if(imageSize == 'tiny' || imageSize == 'small')
		if(!loadedSmall[index]) {
			loadedSmall[index] = new Image(400,300);
			loadedSmall[index].src = getImageURL(index);
		}
		else;
	else
		if(!loadedLarge[index]) {
			loadedLarge[index] = new Image(1040,780);
			loadedLarge[index].src = getImageURL(index);
		}
}

function setSlideIndex(index) {
	setSlideIndexWithReload(index,false);
}

function setSlideIndexWithReload(index, forceReload) {
	if(!isNaN(index)) {
		if(slideIndex != index || forceReload) {
			finishNote();
			if(index < 0)
				index = 0;
			slideIndex = index;
			checkCurrentPreload();
			reloadSlide();
			loadNoteInTextArea();
		}
	}
}

function navigateSlide() {
	doSynchronization(false);
	setSlideIndex(eId('slide_navigation').selectedIndex);
}

function sortParticipants(participants) {
	for(var i=0; i+1<participants.length; i++) {
		var min = i;
		for(var j=i+1; j<participants.length; j++)
			if(participants[j].displayName < participants[min].displayName)
				min = j;
		if(min != i) {
			var temp = participants[min];
			participants[min] = participants[i];
			participants[i] = temp;
		}
	}
}

function sortByTime(notes) {
	for(var i=0; i+1<notes.length; i++) {
		var min = i;
		for(var j=i+1; j<notes.length; j++)
			if(notes[j]["time"] < notes[min]["time"])
				min = j;
		if(min != i) {
			var temp = notes[min];
			notes[min] = notes[i];
			notes[i] = temp;
		}
	}
}

function sortByPerson(notes) {
	var viewerId = wave.getViewer().getId();
	for(var i=0; i+1<notes.length; i++) {
		var min = i;
		for(var j=i+1; j<notes.length; j++)
			if(notes[min]["participantId"] != viewerId && (notes[j]["participantId"] == viewerId || notes[j]["displayName"] < notes[min]["displayName"]))
				min = j;
		if(min != i) {
			var temp = notes[min];
			notes[min] = notes[i];
			notes[i] = temp;
		}
	}
}

function wrapInFinished(note, finished) {
	if(finished)
		return "<span class='finished_note'>"+note+"</span>";
	else
		return "<span class='not_finished_note'>"+note+"</span>";
}

function buildNotes(notes) {
	var newInnerHTML = "";
	var divHeight = parseInt((eId('notes_container').style.height+"").replace('px',''));
	var atTop = ((eId('notes_container').scrollTop + divHeight) >= eId('notes_container').scrollHeight);
	for(var i=0; i<notes.length; i++) {
		newInnerHTML += "<div class='note_item'>"
		newInnerHTML += "<img class='user_pic' src='"+getThumbnailSrc(notes[i]["participantId"])+"' />"
		newInnerHTML += "<b>"+getDisplayName(notes[i]["participantId"])+":</b> "+wrapInFinished(notes[i]["text"],notes[i]["finished"])
		while(i+1 < notes.length && notes[i]["participantId"] == notes[i+1]["participantId"]) {
			i++;
			newInnerHTML += "<br/>" + wrapInFinished(notes[i]["text"],notes[i]["finished"]);
		}
		newInnerHTML += "</div>";
	}
	eId('notes_container').innerHTML = newInnerHTML;
	if (atTop) {
		eId('notes_container').scrollTop = eId('notes_container').scrollHeight;
	}
}

function refreshNotes() {
	var notes = [];
	for(var participantId in peopleNotes)
		if(peopleNotes[participantId]["slide_"+slideIndex])
			for(var i=0; i<peopleNotes[participantId]["slide_"+slideIndex].length; i++)
				if(peopleNotes[participantId]["slide_"+slideIndex][i] != null &&
						peopleNotes[participantId]["slide_"+slideIndex][i]["time"])
					notes[notes.length] = peopleNotes[participantId]["slide_"+slideIndex][i];
	sortByTime(notes);
	if(currentSort == 'person')
		sortByPerson(notes);
	buildNotes(notes);
}

function setNoteIndex() {
	var viewerId = wave.getViewer().getId();
	if(peopleNotes[viewerId] == null || peopleNotes[viewerId]["slide_"+slideIndex] == null ||
			peopleNotes[viewerId]["slide_"+slideIndex].length == 0) {
		return;
	}
	var slideNotes = peopleNotes[viewerId]["slide_"+slideIndex];
	if(slideNotes[slideNotes.length-1]["finished"])
		eId('note_index').value = slideNotes.length;
	else
		eId('note_index').value = slideNotes.length-1;
}

function reloadSlide() {
	eId('slide_image').src = getCurrentImageURL();
	eId('slide_navigation').selectedIndex = slideIndex;
	setNoteIndex();
	refreshNotes();
	refreshPrevSlideButton();
	refreshNextSlideButton();
}

function refreshNextSlideButton() {
	if(slideIndex + 1 >= numberOfSlides)
		eId('next_slide_button').disabled = true;
	else
		eId('next_slide_button').disabled = false;
}

function refreshPrevSlideButton() {
	if(slideIndex <= 0)
		eId('prev_slide_button').disabled = true;
	else
		eId('prev_slide_button').disabled = false;
}

function nextSlide() {
	doSynchronization(false);
	setSlideIndex(slideIndex+1);
}

function prevSlide() {
	doSynchronization(false);
	setSlideIndex(slideIndex-1);
}

function doSynchronization(doSync) {
	var syncButton = eId('stay_synchronized');
	if(doSync) {
		setSlideIndex(parseInt(wave.getState().get("slideIndex")));
		syncButton.disabled = true;
		syncButton.value = "Synchronized.";
	}
	else {
		syncButton.disabled = false;
		syncButton.value = "Stay Synchronized";
	}
}

function stateUpdated() {
	//debugLog("stateUpdated presentationKey=" + wave.getState().get("presentationKey") + ", slideIndex=" + wave.getState().get("slideIndex"))
	var newPresentationState = wave.getState().get("presentationState");
	if(newPresentationState == "selection") {
		if(presentationState != newPresentationState) {
			presentationState = newPresentationState;
			eId('presentation_show_div').style.display = "none";
			if(wave.getViewer() == wave.getHost())
				eId('presentation_setup_div').style.display = "block";
		}
		if(listOfPresentations != wave.getState().get('listOfPresentations'))
			if(wave.getState().get('listOfPresentations') == null)
				updateListOfPresentations(null);
			else
				updateListOfPresentations(eval(wave.getState().get('listOfPresentations')));
		if(wave.getState().get('preferredParticipants') != null && preferredParticipants != eval(wave.getState().get('preferredParticipants'))) {
			updateParticipantList();
		}
		else if(wave.getState().get('currentParticipants') != null && currentParticipants != eval(wave.getState().get('currentParticipants'))) {
			updateParticipantList();
		}
		else {
		}
	}
	else if(newPresentationState == "preStart" || newPresentationState == "started") {
		if(presentationState != newPresentationState) {
			presentationState = newPresentationState;
			eId('presentation_show_div').style.display = "block";
			eId('presentation_setup_div').style.display = "none";
			primaryPoll();
		}
		
		presentation = eval("("+wave.getState().get("presentation")+")");
			
		refreshPresentation();

		repopulatePeopleNotes();
		refreshNotes();
	}
	gadgets.window.adjustHeight();
}

function waveParticipantsChanged() {
	var participants = wave.getParticipants();
	for(var i=0; i<participants.length; i++) {
		var participant = {"id":participants[i].getId(), 
			"displayName":participants[i].getDisplayName(),
			"thumbnailURL":participants[i].getThumbnailUrl()};
		if(!containsParticipant(preferredParticipants,participant))
			preferredParticipants.push(participant);
		if(!contains(currentParticipants,participant.id))
			currentParticipants.push(participant.id);
	}
	updateParticipantObjects();
	storeParticipantLists();
	gadgets.window.adjustHeight();
}

function refreshPresentation() {
	if (null != presentation) {
		if (0 == numberOfSlides || presentation.slides.length != numberOfSlides) {
			numberOfSlides = presentation.slides.length;
			refreshNumberOfSlides();
		}
		
		if (getIsSynchronized()) {
			setSlideIndex(parseInt(presentation.currentSlideIndex));
		}
	}
}

function showSelectPresentation(show) {
	//debugLog("show: "+show+"; eId('presentation_selector').selectedIndex: "+eId('presentation_selector').selectedIndex+"; presentationKey: "+presentationKey);
	var selector = eId('presentation_selector');
	if(show) {
		presentationKey = "";
		selector.selectedIndex = -1;
		eId('presentation_selected_div').style.display = 'none';
		eId('select_presentation_div').style.display = 'block';
	}
	else {
		if(selector.selectedIndex >= 0) {
			presentationKey = selector.options[selector.selectedIndex].value;
			eId('presentation_selected_div').innerHTML = "Selected: "+selector.options[selector.selectedIndex].text;
		}
		else {
			presentationKey = "";
			eId('presentation_selected_div').innerHTML = "Selected: None";
		}
		eId('presentation_selected_div').style.display = 'inline';
		eId('select_presentation_div').style.display = 'none';
	}
	enableDisableStart();
}

/**
 * Callback for presentation servlet json ajax request.
 * @param {Object} json
 */
function setPresentation(json) {
	//debugLog("set presentation " + json.toString());
	wave.getState().submitValue("presentation", JSON.stringify(json));
	presentation = json;
	refreshPresentation();
}

function secondaryPoll() {
	lastPollDate = wave.getState().get("lastPollDate")
	/*debugLog("secondary poll - num=" + wave.getState().get("numberOfSlides")
        + ", current=" + wave.getState().get("slideIndex")
		+ ", sinceprimary=" + (wave.getTime() - lastPollDate)
		+ ", primary=" + wave.getState().get("primaryPoller"));
		*/
	if (null == lastPollDate || wave.getTime() - lastPollDate > pollTakeoverTimeout) {
		//debugLog("attempt to become primary");
		setAsPoller();
	} else {
		//debugLog("reschedule secondary");
		setTimeout("secondaryPoll();", secondaryPollInterval);
	}
}


function primaryPoll(check) {
	//debugLog("primary poll - num=" + wave.getState().get("numberOfSlides") + ", current=" + wave.getState().get("slideIndex"));
	if (check && wave.getState().get("primaryPoller") != wave.getViewer().getId()) {
		//debugLog("drop to secondary");
		secondaryPoll();
	} else {
		wave.getState().submitValue("lastPollDate", wave.getTime());
		
        $.getJSON('http://wave-notes.appspot.com/presentation?presentationKey=' + presentationKey + "&jsoncallback=?", 
            setPresentation);
			
		setTimeout("primaryPoll(true);", primaryPollInterval);
	}
}

function setAsPoller() {
	//debugLog("set me as poller");
	wave.getState().submitValue("primaryPoller", wave.getViewer().getId());
	
	primaryPoll(false);
}

function initializeGadget() {

	var data = {};
	var presentationState = wave.getState().get("presentationState");
	if(presentationState == null || presentationState == "selection") {
		data["presentationState"] = "selection";
		if(wave.getViewer() == wave.getHost()) {
			eId('presentation_setup_div').style.display = "block";
			showSelectPresentation(true);
		}
	}
	if(wave.getState().get("presentationKey") != null)
		presentationKey = wave.getState().get("presentationKey");
		
	updateParticipantList();
	
	stateUpdated();
	
	setSlideIndexWithReload(slideIndex, true);
	
	wave.setParticipantCallback(waveParticipantsChanged);
	wave.setStateCallback(stateUpdated);
	if(data.presentationState != null)
		wave.getState().submitDelta(data);
	
	if(presentationState != null && presentationState != "selection")
		secondaryPoll();
}

function init() {
	if (wave && wave.isInWaveContainer())
		wave.setStateCallback(initializeGadget);
}

gadgets.util.registerOnLoadHandler(init);